/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.jeedcp.gen.utils;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jeedcp.gen.entity.ColumnEntity;
import com.jeedcp.gen.entity.GenColumn;
import com.jeedcp.gen.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class GenUtils {

    public static List<String> getTemplates(String templateName,Boolean hasRefTable) {
        List<String> templates = new ArrayList<String>();
//        Model,Service,Mapper
        if(templateName.contains("backend")) {
            templates.add("template/backend/Entity.java.vm");
            templates.add("template/backend/Dao.java.vm");
//        templates.add("template/backend/Dao.xml.vm");
            templates.add("template/backend/Service.java.vm");
            templates.add("template/backend/ServiceImpl.java.vm");
            templates.add("template/backend/DTO.java.vm");
            templates.add("template/backend/Controller.java.vm");
//            templates.add("template/backend/Excel.java.vm");
        }
        if(templateName.contains("View")) {
            templates.add("template/front/index.vue.vm");
            templates.add("template/front/index.js.vm");
            templates.add("template/front/add-or-update.vue.vm");
        }
        if(templateName.contains("sql")) {
            templates.add("template/backend/mysql.vm");
        }

        if(templateName.contains("uniapp")) {
            templates.add("template/uniapp/index.vue.vm");
            templates.add("template/uniapp/index.js.vm");
            templates.add("template/uniapp/add-or-update.vue.vm");
            templates.add("template/uniapp/info.vue.vm");
            if(hasRefTable) {
                templates.add("template/uniapp/fuzzy-search.vue.vm");
            }
        }

        if(templateName.contains("android")) {
            templates.add("template/android/Entity.java.vm");
            templates.add("template/android/entity_add.xml.vm");
            templates.add("template/android/entity_view.xml.vm");
            templates.add("template/android/EntityActivity.java.vm");
            templates.add("template/android/EntityAddActivity.java.vm");
            templates.add("template/android/EntityListAdapter.java.vm");
            templates.add("template/android/EntityListFragment.java.vm");
            templates.add("template/android/EntityViewActivity.java.vm");
        }
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<GenColumn> columsList,String templateName) {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        Boolean hasRefTable =false;
        for (GenColumn columnEntity : columsList) {
            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttr(StringUtils.uncapitalize(attrName));
            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getColType().split("\\(")[0].trim(), "unknowType");
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }

            if(columnEntity.getRefTable()!=null) {
                String refClassName = tableToJava(columnEntity.getRefTable(), config.getString("tablePrefix"));
                columnEntity.setRefClassName(refClassName);
                columnEntity.setRefClass(StringUtils.uncapitalize(refClassName));
                if("T".equals(columnEntity.getRefType())){
                    hasRefTable = true;
                }
            }
//            //是否主键
//            if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) {
//                tableEntity.setPk(columnEntity);
//            }
        }
        tableEntity.setColumns(columsList);
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("version", config.getString("version"));
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("date", DateUtils.format(new Date(), DateUtils.DATE_PATTERN));

        for (int i = 0; i <= 10; i++) {
            map.put("id" + i, IdWorker.getId());
        }

        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates(templateName,hasRefTable);
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                String fileName = getFileName(template, tableEntity.getClassName(),
                        config.getString("package"), config.getString("moduleName"));
                System.out.println(fileName);
                com.jeedcp.gen.utils.IOUtils.createFiles(sw, fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("jeedcp.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        Configuration config = getConfig();
        String basePath =  GenUtils.class.getResource("/").getPath().toString();
        basePath=basePath.substring(0,basePath.indexOf("parent"));
        basePath=basePath.substring(0,basePath.lastIndexOf("/")+1);
        String entityPath =  basePath+config.getString("output.path.entity");
//        String excelPath =   basePath+config.getString("output.path.excel");
        String dtoPath =  basePath+ config.getString("output.path.dto");
        String servicePath =  basePath+ config.getString("output.path.service");
        String daoPath =   basePath+config.getString("output.path.dao");
        String controllerPath =   basePath+config.getString("output.path.controller");
        String viewPath =  basePath+ config.getString("output.path.view");
        String apijsPath =  basePath+ config.getString("output.path.apijs");

        String univiewPath =  basePath+ config.getString("output.path.uniview");
        String uniapijsPath =  basePath+ config.getString("output.path.uniapijs");

        String androidXmlPath =  basePath+ config.getString("output.path.androidXmlPath");
        String androidSrcPath =  basePath+ config.getString("output.path.androidSrcPath");

        String sqlPath =  basePath+ config.getString("output.path.sql");
        if (template.contains("template/backend/Entity.java.vm")) {
            return entityPath + className + ".java";
        }

//        if (template.contains("template/backend/Excel.java.vm")) {
//            return excelPath + className + "Excel.java";
//        }

        if (template.contains("template/backend/Dao.java.vm")) {
            return daoPath+ className + "Mapper.java";
        }

        if (template.contains("template/backend/Service.java.vm")) {
            return servicePath +"I" + className + "Service.java";
        }

        if (template.contains("template/backend/ServiceImpl.java.vm")) {
            return servicePath  + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("template/backend/Controller.java.vm")) {
            return controllerPath  + className + "Controller.java";
        }

//        if (template.contains("Dao.xml.vm")) {
//            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "Dao.xml";
//        }

        if (template.contains("template/backend/DTO.java.vm")) {
            return dtoPath+ className + "DTO.java";
        }

        if (template.contains("template/front/index.vue.vm")) {
            return viewPath + className.toLowerCase()  + File.separator + className.toLowerCase() + ".vue";
        }

        if (template.contains("template/front/add-or-update.vue.vm")) {
            return viewPath + className.toLowerCase()  + File.separator + className.toLowerCase() + "-add-or-update.vue";
        }

        if (template.contains("template/front/index.js.vm")) {
            return apijsPath  + className.toLowerCase() + ".js";
        }

        if (template.contains("template/backend/mysql.vm")) {
            return sqlPath+className.toLowerCase() + ".mysql.sql";
        }

        //Uniapp
        if (template.contains("template/uniapp/index.vue.vm")) {
            return univiewPath +className.toLowerCase()  + File.separator + "index.vue";
        }
        if (template.contains("template/uniapp/add-or-update.vue.vm")) {
            return univiewPath + className.toLowerCase()  + File.separator  + "add-or-update.vue";
        }
        if (template.contains("template/uniapp/info.vue.vm")) {
            return univiewPath + className.toLowerCase()  + File.separator  + "info.vue";
        }
        if (template.contains("template/uniapp/fuzzy-search.vue.vm")) {
            return univiewPath + className.toLowerCase()  + File.separator  + "fuzzy-search.vue";
        }
        if (template.contains("template/uniapp/index.js.vm")) {
            return uniapijsPath  + className.toLowerCase() + ".js";
        }



        //Android

        if (template.contains("template/android/entity_add.xml.vm")) {
            return androidXmlPath  + File.separator  + className.toLowerCase() + "_add.xml";
        }
        if (template.contains("template/android/entity_view.xml.vm")) {
            return androidXmlPath  + File.separator  + className.toLowerCase() + "_view.xml";
        }

        if (template.contains("template/android/Entity.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className + ".java";
        }
        if (template.contains("template/android/EntityActivity.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className+ "Activity.java";
        }
        if (template.contains("template/android/EntityAddActivity.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className+ "AddActivity.java";
        }
        if (template.contains("template/android/EntityListAdapter.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className + "ListAdapter.java";
        }
        if (template.contains("template/android/EntityListFragment.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className + "ListFragment.java";
        }
        if (template.contains("template/android/EntityViewActivity.java.vm")) {
            return androidSrcPath+ className.toLowerCase()  + File.separator  + className + "ViewActivity.java";
        }





        return null;
    }
}
